package com.will.seed.websocket;

import java.util.List;
import java.util.Map;

import io.netty.channel.ChannelHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpUtil;
import io.netty.handler.codec.http.HttpVersion;
import io.netty.handler.codec.http.QueryStringDecoder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;

/**
 * Created by xiaoEigth on 2018/8/17.
 */
@Slf4j
@ChannelHandler.Sharable
public class HttpRequestHandler  extends SimpleChannelInboundHandler<FullHttpRequest> {

    @Value("${ws.path:/websocket}")
    private String wsUri;

    @Autowired
    private RedisMessageListenerContainer container;


    @Override
    protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception {
        log.info("===========> {}, {}", wsUri, request.uri());

        String uri = StringUtils.substringBefore(request.uri(), "?");
        if(wsUri.equalsIgnoreCase(uri)) {
            QueryStringDecoder query = new QueryStringDecoder(request.uri());
            Map<String, List<String>> map = query.parameters();
            List<String> tokens = map.get("token");

            if(tokens != null && !tokens.isEmpty()) {
                String token = tokens.get(0);
                //save session
                ChannelManager.getInstance().getChannelCtxMap().put(token, ctx);
                ctx.channel().attr(Constants.CHANNEL_TOKEN_KEY).getAndSet(token);
                request.setUri(uri);
                ctx.fireChannelRead(request.retain());

                //sub token for sync pub
                addSyncReceiver(token);
            }else{
                send403ContinueExpected(ctx);
            }
        }else {
            if(!HttpUtil.is100ContinueExpected(request)) {
                send403ContinueExpected(ctx);
            }
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }

    private void send100ContinueExpected(ChannelHandlerContext ctx) {
        FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.CONTINUE);
        ctx.writeAndFlush(response);
    }

    private void send403ContinueExpected(ChannelHandlerContext ctx) {
        FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.FORBIDDEN);
        ctx.writeAndFlush(response);
    }

    private void addSyncReceiver(String token){
        if(ChannelManager.getInstance().getReceiverMap().containsKey(token))
            return;

        SyncReceiver syncReceiver = new SyncReceiver(token);
        container.addMessageListener(syncReceiver,
                new PatternTopic(token));
        ChannelManager.getInstance().getReceiverMap().putIfAbsent(token,syncReceiver);
    }
}
